package com.robotics

import hudson.model.AbstractItem

import java.sql.*
import java.util.ArrayList
import java.util.HashMap
import java.util.List

import jenkins.model.Jenkins
import org.jenkinsci.plugins.database.Database
import org.jenkinsci.plugins.database.GlobalDatabaseConfiguration
import org.kohsuke.stapler.Ancestor
import org.kohsuke.stapler.Stapler
import org.kohsuke.stapler.StaplerRequest2
import java.util.UUID

class DataBaseUtils {

    //数据库执行
    def  executeSql(String sql, List<String> params) {
        Connection connection = null
        try {
            System.err.println('executeSql:' + sql)
            if (GlobalDatabaseConfiguration.get() == null) {
                return false
            }
            Database database = GlobalDatabaseConfiguration.get().getDatabase()
            if (database.getDescriptor().getDisplayName().equals('MySQL')) {
                connection = database.getDataSource().getConnection()
                if (!connection.isClosed()) {
                    PreparedStatement prepareStatement = connection.prepareStatement(sql)
                    for (int i = 0; i < params.size(); i++) {
                        if (params.get(i) instanceof Integer) {
                            prepareStatement.setInt(i + 1, (Integer) params.get(i))
                        } else if (params.get(i) instanceof Long) {
                            prepareStatement.setLong(i + 1, (Long) params.get(i))
                        } else if (params.get(i) instanceof Boolean) {
                            prepareStatement.setBoolean(i + 1, (Boolean) params.get(i))
                        } else if (params.get(i) instanceof Double) {
                            prepareStatement.setDouble(i + 1, (Double) params.get(i))
                        } else if (params.get(i) instanceof Float) {
                            prepareStatement.setFloat(i + 1, (Float) params.get(i))
                        } else {
                            prepareStatement.setString(i + 1, params.get(i).toString())
                        }
                    }
                    boolean res = prepareStatement.execute()
                    connection.close()
                    return !res
                } else {
                    System.err.println('sql error: connection is closed')
                }
            } else {
                System.err.println('sql error: database is not MySQL')
            }
        } catch (SQLException e) {
            e.printStackTrace()
        } catch (Exception e) {
            //            System.err.println("sql error:" + e.getMessage());
            e.printStackTrace()
        }
        if (connection != null && !connection.isClosed()) { connection.close() }
    }

    def  List<HashMap<String, Object>>   executeQuery(String sql, List<String> params) {
        List<HashMap<String, Object>> list = new ArrayList<>()
        Connection connection = null
        try {
            System.err.println('executeSql:' + sql)
            if (GlobalDatabaseConfiguration.get() == null) {
                return false
            }
            Database database = GlobalDatabaseConfiguration.get().getDatabase()
            if (database.getDescriptor().getDisplayName().equals('MySQL')) {
                connection = database.getDataSource().getConnection()
                if (!connection.isClosed()) {
                    PreparedStatement prepareStatement = connection.prepareStatement(sql)
                    for (int i = 0; i < params.size(); i++) {
                        if (params.get(i) instanceof Integer) {
                            prepareStatement.setInt(i + 1, (Integer) params.get(i))
                        } else if (params.get(i) instanceof Long) {
                            prepareStatement.setLong(i + 1, (Long) params.get(i))
                        } else if (params.get(i) instanceof Boolean) {
                            prepareStatement.setBoolean(i + 1, (Boolean) params.get(i))
                        } else if (params.get(i) instanceof Double) {
                            prepareStatement.setDouble(i + 1, (Double) params.get(i))
                        } else if (params.get(i) instanceof Float) {
                            prepareStatement.setFloat(i + 1, (Float) params.get(i))
                        } else {
                            prepareStatement.setString(i + 1, params.get(i).toString())
                        }
                    }
                    ResultSet resultSet = prepareStatement.executeQuery()
                    while (resultSet.next()) {
                        ResultSetMetaData metaData = resultSet.getMetaData()
                        HashMap<String, Object> map = new HashMap<>()
                        for (int i = 1; i <= metaData.getColumnCount(); i++) {
                            map.put(metaData.getColumnName(i), resultSet.getObject(i))
                        }
                        list.add(map)
                    }
                    connection.close()
                } else {
                    System.err.println('sql error: connection is closed')
                }
            } else {
                System.err.println('sql error: database is not MySQL')
            }
        } catch (SQLException e) {
            e.printStackTrace()
        } catch (Exception e) {
            //            System.err.println("sql error:" + e.getMessage());
            e.printStackTrace()
        }
        if (connection != null && !connection.isClosed()) { connection.close() }
        return null
    }

    //数据库查询
    def List<HashMap<String, Object>>   executeQuery(String sql) {
        List<HashMap<String, Object>> list = new ArrayList<>()
        Connection connection = null
        try {
            System.err.println('executeQuery')
            if (GlobalDatabaseConfiguration.get() == null) {
                return list
            }
            Database database = GlobalDatabaseConfiguration.get().getDatabase()
            if (database.getDescriptor() != null &&
                    database.getDescriptor().getDisplayName().equals('MySQL')) {
                connection = database.getDataSource().getConnection()
                if (!connection.isClosed()) {
                    PreparedStatement prepareStatement = connection.prepareStatement(sql)
                    ResultSet resultSet = prepareStatement.executeQuery()
                    while (resultSet.next()) {
                        ResultSetMetaData metaData = resultSet.getMetaData()
                        HashMap<String, Object> map = new HashMap<>()
                        for (int i = 1; i <= metaData.getColumnCount(); i++) {
                            map.put(metaData.getColumnName(i), resultSet.getObject(i))
                        }
                        list.add(map)
                    }
                    System.err.println('executeQuery  size ' +
                                       list.size())
                    connection.close()
                    return list
                } else {
                //                    System.err.println("sql error: connection is
                //                    closed");
                }
            } else {
                    //                System.err.println("sql error: database is not
                    //                MySQL");
                    }
        } catch (SQLException e) {
            e.printStackTrace()
        } catch (Exception e) {
            //            System.err.println("sql error:" + e.getMessage());
            e.printStackTrace()
        }
        if (connection != null && !connection.isClosed()) { connection.close() }
        return null
    }

    def checkNeedBUild(Map params) {
        def package_name = params.package_name
        def unique_id  = params.commitId
        def project_name = params.project_name
        def framework = System.getProperty('os.arch')
        List<HashMap<String, Object>> list = executeQuery('select * from repository_info where is_valid=true and package_name= ? and unique_id =? and project_name=? and framework=?;', [package_name, unique_id, project_name, framework]);
        if (list.size() == 0) {
            return true
        }
        return true
    }

    def addRepositoryInfo(Map params) {
        def package_name = params.package_name
        def project_name = params.project_name
        def unique_id  = params.commitId
        def timestamp  = params.package_time
        def version  = params.version
        def framework = System.getProperty('os.arch')
        UUID randomUUID = UUID.randomUUID()
        List<HashMap<String, Object>> list = executeQuery('select * from repository_info where is_valid=true and package_name= ? and unique_id =? and project_name=? and framework=?;', [package_name, unique_id, project_name, framework]);
        if (list.size() > 0) {
            executeSql('update repository_info set is_valid =false where is_valid=true and package_name= ? and unique_id =? and project_name=? and framework=?;', [package_name, unique_id, project_name, framework]);
        }
        return executeSql('insert into repository_info(id, package_name, unique_id, is_valid, version, timestamp, project_name, framework) values(?, ?, ?, ?, ?, ?,?,?)', [randomUUID.toString(), package_name, unique_id, true, version, timestamp, project_name, framework])
    }

}

def utils = new com.robotics.DataBaseUtils()
def params = [:]
params['package_name'] = 'com.robotics'
params['commitId'] = '123456'
params['version'] = '1.0.0'
params['package_time'] = 1231123
params['project_name'] = "project_name"
def res = utils.addRepositoryInfo(params)
println "${res}"
